package org.shj.tdpl.loader.loader.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.shj.tdpl.common.constant.TdplConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ShenHuangJian
 * @date 2018年6月28日
 *
 */
@Slf4j
public class SingleFileDataLoader extends AbstractXlsxDataLoader{

	@Override
	protected void loadData(List<String> tables, int... versions) throws Exception{
		List<String> insertMap = new ArrayList<String>();
		List<String> deleteMap = new ArrayList<String>();
		List<String> updateAfterInsertMap = new ArrayList<String>();
		List<String> updateBeforeDelMap = new ArrayList<String>();
		
		InputStream ins = null;
		try{
			ins = new FileInputStream(generatedFilePath + File.separator + TdplConstants.Single_Schema_File_Name + ".xlsx");
			XSSFWorkbook book = new XSSFWorkbook(ins);
			FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
			
			for(String tbl : tables){
				XSSFSheet sheet = book.getSheet(tbl);
				getSqlsNeedToBeExecute(sheet, evaluator, insertMap, deleteMap, updateAfterInsertMap, updateBeforeDelMap, versions);		
			}
			
			executeSqls(insertMap, deleteMap, updateAfterInsertMap, updateBeforeDelMap);
			
		}catch(Exception e){
			log.error("Error when reading excel.");
			throw e;
			
		}finally{
			if(ins != null){
				ins.close();
			}
		}
		
	}

	@Override
	protected XSSFWorkbook getCommonInfoBook() throws Exception{
		InputStream ins = null;
		try{
			ins = new FileInputStream(generatedFilePath + File.separator + TdplConstants.Single_Schema_File_Name + ".xlsx");
			XSSFWorkbook book = new XSSFWorkbook(ins);
			return book;
		}catch(Exception e){
			log.error("Error when reading excel.");
			throw e;
			
		}finally{
			if(ins != null){
				ins.close();
			}
		}
	}

}
